//
//  MLRequestCache.m
//  MSHandbook
//
//  Created by molon on 15/1/27.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "MLRequestCache.h"
#import "MLSecurity.h"
#import "NSString+MLKit.h"

#define kCacheRequestDirName @"MolonRequestCache"
//TODO: 有空把io弄成私有队列
@implementation MLRequestCache

+ (NSString*)cacheFilePathWithURL:(NSString*)url andRequestParameters:(NSDictionary*)parameters
{
    
    NSString *getPars = [url stringByAppendingString:@"?"];
    for (NSString *key in [parameters allKeys]) {
        getPars = [getPars stringByAppendingFormat:@"%@=%@&",key,parameters[key]];
    }
    
    return [MLRequestCache cacheFilePathWithFileName:[MLSecurity md5String:getPars]];
    
}

+ (id)responseObjectWithCacheFilePath:(NSString*)cacheFilePath
{
    if ([NSString IsNilOrEmpty:cacheFilePath]) {
        return nil;
    }
    //读取缓存文件
    return [NSKeyedUnarchiver unarchiveObjectWithFile:cacheFilePath];
}

+ (MLRequestCacheState)stateForCacheFilePath:(NSString*)cacheFilePath andValidTime:(NSTimeInterval)validTime
{
    if ([NSString IsNilOrEmpty:cacheFilePath]) {
        return MLRequestCacheStateNotExisted;
    }
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:cacheFilePath isDirectory:nil]) {
        return MLRequestCacheStateNotExisted;
    }
    
    NSError *error = nil;
    NSDictionary *attributes = [fileManager attributesOfItemAtPath:cacheFilePath
                                                             error:&error];
#ifdef DEBUG
    if (error) {
        DLOG(@"get attributes of %@ error:%@",cacheFilePath,error);
    }
#endif
    if (!attributes) {
        return MLRequestCacheStateNotExisted;
    }
    
    //检测是否过期
    if (-[[attributes fileModificationDate] timeIntervalSinceNow]>validTime) {
        return MLRequestCacheStateExpired;
    }

    return MLRequestCacheStateValid;
}

+ (BOOL)cacheResponseObject:(id)responseObject toCacheFilePath:(NSString*)cacheFilePath
{
    if ([NSString IsNilOrEmpty:cacheFilePath]) {
        return NO;
    }
    
    return [NSKeyedArchiver archiveRootObject:responseObject toFile:cacheFilePath];
}

#pragma mark - base cache dir
+ (BOOL)createBaseDirectoryAtPath:(NSString *)path {
    __autoreleasing NSError *error = nil;
    [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES
                                               attributes:nil error:&error];
    if (error) {
        DLOG(@"建立文件夹失败:%@",error);
        return NO;
    }
    return YES;
}

+ (NSString*)cacheFilePathWithFileName:(NSString*)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths[0] stringByAppendingPathComponent:kCacheRequestDirName];
    
    //检测dir是否存在，不存在需要建立
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir;
    if (![fileManager fileExistsAtPath:cacheDir isDirectory:&isDir]) {
        if([MLRequestCache createBaseDirectoryAtPath:cacheDir]){
            return nil;
        }
    } else {
        if (!isDir) {
            NSError *error = nil;
            [fileManager removeItemAtPath:cacheDir error:&error];
            if([MLRequestCache createBaseDirectoryAtPath:cacheDir]){
                return nil;
            }
        }
    }
    
    //拼接
    return [cacheDir stringByAppendingPathComponent:fileName];
}

+ (BOOL)clear
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = [paths[0] stringByAppendingPathComponent:kCacheRequestDirName];
    
    
    NSError *error = nil;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:cacheDir error:&error];
}

@end
